package com.example.saifly.inPageRecord;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;
import com.example.saifly.inPageRecord.RecordModel.EnvironmentData;

import java.io.IOException;
import java.util.Date;

import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class WriteEnvironmentActivity extends Activity {

    private TextView tvHeat,tvHumity,tvPm;//tv展示各项指标
    private RelativeLayout rlHeat,rlHumity,rlPm;
    private Button btSubmit;
    private int heat,humity,pm;//获取环境指标
    private ImageView ivReturn;
    private EnvironmentData environmentData= new EnvironmentData();//环境信息实体
    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_write_environment_data;
    }
    private SharedPreferences sharedPreferences;

    @Override
    protected void init() {
        super.init();
        sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        rlHeat=findViewById(R.id.write_environment_data_heat);
        rlHumity=findViewById(R.id.write_environment_data_humidity);
        rlPm=findViewById(R.id.write_environment_data_pm25);

        tvHumity=findViewById(R.id.write_environment_data_humidity_show);
        tvHeat=findViewById(R.id.write_environment_data_heat_show);
        tvPm=findViewById(R.id.write_environment_data_pm25_show);

        ivReturn=findViewById(R.id.write_environment_data_return);
        btSubmit=findViewById(R.id.write_environment_data_submit);

        updateUi();
        rlHeat.setOnClickListener(new addListeners());
        rlHumity.setOnClickListener(new addListeners());
        rlPm.setOnClickListener(new addListeners());
        btSubmit.setOnClickListener(new addListeners());
        doJump();

    }



    /**
     * 创建日期：2019/12/8 20:05
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明： 页面跳转
     */

    private  void doJump()
    {
        ivReturn.setOnClickListener(view -> finish());
    }


    /**
     * 创建日期：2019/12/11 22:28
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明： 刷新页面
     */

    private void  updateUi()
    {
        String phoneNum = sharedPreferences.getString("uid", "default");
        Date date =new Date();
        new Thread(new Runnable() {
            @Override
            public void run() {
                EnvironmentGetData(phoneNum,date);
            }
        }).start();
    }


    /**
     * 创建日期：2019/12/7 17:42
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明：湿度选择器
     */
    private void initHumityPicker() {
        NumberPicker humityPicker = new NumberPicker(this);

        humityPicker.setOffset(2);//偏移量
        humityPicker.setRange(1, 100);//数字范围
        humityPicker.setSelectedItem(55);
        humityPicker.setLabel("%");
        humityPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener()
        {
            @Override
            public void onOptionPicked(String option)
            {
                tvHumity.setText(option+"%");
            }
        });
        humityPicker.show();

    }

    /**
     * 创建日期：2019/12/7 17:41
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明： pm2.5选择器
     */
    private void initPmPicker() {
        NumberPicker pmPicker = new NumberPicker(this);
        pmPicker.setOffset(2);//偏移量
        pmPicker.setRange(1, 400);//数字范围
        pmPicker.setSelectedItem(60);
        pmPicker.setLabel("微克");
        pmPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option)
            {
                tvPm.setText(option+"微克");
            }
        });
        pmPicker.show();
    }

    /**
     * 创建日期：2019/12/7 17:41
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明：环境温度选择器
     */
    private void initHeatPicker() {
        NumberPicker heatPicker = new NumberPicker(this);
        heatPicker.setOffset(2);//偏移量
        heatPicker.setRange(-30, 45);//数字范围
        heatPicker.setSelectedItem(10);
        heatPicker.setLabel("℃");
        heatPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option)
            {
                heat = Integer.valueOf(option);
                tvHeat.setText(option+"℃");
            }
        });
        heatPicker.show();
    }

    private int getDate(String str)
    {
        int temp;
        String tmp="";
        for(int i=0;i<str.length();i++)
        {
            if (str.charAt(i)>'9'||str.charAt(i)<'0') {
                break;
            }
            else
            {
                tmp+=str.charAt(i);
            }
        }

        temp=Integer.parseInt(tmp);
        return temp;
    }

    private  void analyse() {


        humity = getDate(tvHumity.getText().toString());
        pm = getDate(tvPm.getText().toString());
    }

    /**
     * 创建日期：2019/12/16 18:50
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明： EnvironmentSetData将填写的环境数据保存到数据库的接口；
     * 获取数据库中环境数据的接口
     */
    private interface ApiEnvironmentSetData
    {
        @Headers({"Content-Type:application/json"})
        @POST("/plan/submitEnvironmentData")
        Call<ResponseBody> EnvironmentSetData(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getEnvironmentData")///
        Call<ResponseBody> EnvironmentGetData(@Body JSONObject jsonObject);

    }

    private void EnvironmentSetData(EnvironmentData environmentData)
    {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        ApiEnvironmentSetData apiEnvironmentSetData = retrofit.create(ApiEnvironmentSetData.class);

        JSONObject jsonObject = new JSONObject();
        String jsonString = JSON.toJSONString(environmentData);
        jsonObject.put("environmentData",jsonString);
        Log.d("writeenviron", "EnvironmentSetData: "+jsonObject.toString());

        Call<ResponseBody> call = apiEnvironmentSetData.EnvironmentSetData(jsonObject);
        final Response<ResponseBody> response;

        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                  //  dailyQesFinish = (int) result.get("result");
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WriteEnvironmentActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(WriteEnvironmentActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }

    }

    private void EnvironmentGetData(String patient_phone,Date date) {
        Long dateLong = date.getTime();
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        ApiEnvironmentSetData apiEnvironmentSetData = retrofit.create(ApiEnvironmentSetData.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("patientPhone", patient_phone);
        jsonObject.put("date", dateLong);
        Log.d("getdate", "EnvironmentGetData: " + jsonObject.toString());

        Call<ResponseBody> call = apiEnvironmentSetData.EnvironmentGetData(jsonObject);
        final Response<ResponseBody> response;

        try {
            response = call.execute();
            if (response.body() != null) {
                JSONObject result = JSON.parseObject(response.body().string());
                if (result.getInteger("code") != null && result.getInteger("code") == 1) {
                    JSONObject resultJson = result.getJSONObject("result");
                    String resultData = resultJson.getString("environmentData");
                    EnvironmentData environmentData = JSON.parseObject(resultData, EnvironmentData.class);

                    Log.d("resultxx", "EnvironmentGetData: " + environmentData);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            heat=environmentData.getTemperature();
                            if(environmentData.getTemperature()==-200)
                            {
                                tvHeat.setText("0℃");
                            }
                            else
                            {
                                tvHeat.setText(String.valueOf(heat) + "℃");
                            }

                            tvPm.setText(environmentData.getPm25().toString() + "微克");
                            tvHumity.setText(environmentData.getHumidity().toString() + "%");
                        }
                    });
                    //这里放正常流程操作
                    //  dailyQesFinish = (int) result.get("result");
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WriteEnvironmentActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(WriteEnvironmentActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    /**
     * 创建日期：2019/12/7 17:43
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明： 响应事件
     */
    private class addListeners implements View.OnClickListener
    {
        @Override
        public void onClick (View v)
        {
            switch (v.getId())
            {
                case R.id.write_environment_data_heat:
                    initHeatPicker();
                    break;
                case R.id.write_environment_data_submit:
                    doSubmit();
                    WriteEnvironmentActivity.this.finish();
                    break;
                case R.id.write_environment_data_humidity:
                    initHumityPicker();
                    break;
                case R.id.write_environment_data_pm25:
                    initPmPicker();
                    break;
                default:
                    break;
            }
        }
    }
    private void doSubmit()
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(WriteEnvironmentActivity.this,"信息已保存",Toast.LENGTH_SHORT).show();
            }
        });
        analyse();
        SharedPreferences preferences = getSharedPreferences("config", MODE_PRIVATE);
        String phoneNum=preferences.getString("uid","default");
        environmentData.setPatientPhone(phoneNum);
        environmentData.setTemperature(heat);
        environmentData.setPm25(pm);
        environmentData.setHumidity(humity);

        Date date = new Date();
        environmentData.setDate(date);
//        EnvironmentSetData(environmentData);
        new Thread(new Runnable() {
            @Override
            public void run() {
                EnvironmentSetData(environmentData);
            }
        }).start();

    }

}
